import Vue from 'vue'
import Vuex from 'vuex'
import ls from '../utils/localStorage'
import router from '../router'

Vue.use(Vuex)

const state = {
  user: ls.getItem('user'),
  auth: ls.getItem('auth'),
}

const mutations = {
  UPDATE_USER(state, user) {
    state.user = user
    ls.setItem('user', user)
  },
  UPDATE_AUTH(state, auth) {
    state.auth = auth
    ls.setItem('auth', auth)
  },
  UPDATE_ACCESS_TOKEN(state, access) {
    ls.setItem('access_token', access.access_token)
    ls.setItem('access_token_expired_at', new Date().getTime() + access.expires_in * 1000)
  }
}

const actions = {
  login({ commit }, user) {
    if (user) commit('UPDATE_USER', user)
    commit('UPDATE_AUTH', user.meta.access_token)
    commit('UPDATE_ACCESS_TOKEN', user.meta)
    router.push('/')
  },
  logout({ commit }) {
    commit('UPDATE_AUTH', false)
    commit('UPDATE_USER', false)
    ls.removeItem('access_token')
    ls.removeItem('access_token_expired_at')
    router.push({ name: 'home', params: { logout: true } })
  },
  update_auth({ commit }, auth) {
    commit('UPDATE_AUTH', auth)
  }
}

const store = new Vuex.Store({
  state,
  mutations,
  actions
})

export default store
